﻿using System;
using System.Text.RegularExpressions;
using System.Web;
using YuYuKiCms.Bl.Interface;

namespace YuYuKiCms.Bl.Core
{
    internal class ChangeLanguageBL : IChangeLanguageBL
    {
        public bool ChangeCulture(HttpRequestBase request, string lang, ref string returnUrl)
        {
            if (request == null || string.IsNullOrWhiteSpace(returnUrl))
                return false;

            returnUrl = returnUrl.Substring(request.ApplicationPath.Length);

            var result = false;
            // url is build like : /FR/... or /EN/...
            // 1. Remove /FR or /EN if exsist
            // 2. Insert /language

            // Check if url is localized well formed
            if (Regex.Match(returnUrl, "^/[a-z]{2}/").Success)
            {
                result = true;
                returnUrl = request.ApplicationPath + returnUrl
                    .Remove(0, returnUrl.IndexOf("/", 1, StringComparison.OrdinalIgnoreCase))
                    .Insert(0, string.Format("/{0}", lang));
            }

            return result;
        }
    }
}